package com.mico.example.springboot.jpa.multi.config;

import com.mico.example.springboot.jpa.multi.domain.primary.User;
import com.mico.example.springboot.jpa.multi.repository.primary.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.HashMap;

@Configuration
@EnableJpaRepositories(
        entityManagerFactoryRef="entityManagerPrimary",
        transactionManagerRef="transactionManagerPrimary",
        basePackages = "com.mico.example.springboot.jpa.multi.repository.primary" //指定repo的位置
)
public class PrimaryConfig {

    @Autowired
    private DataSource primaryDataSource;


    @Primary
    @Bean
    PlatformTransactionManager transactionManagerPrimary() {
        return new JpaTransactionManager(entityManagerPrimary().getObject());
    }

    @Primary
    @Bean(name = "entityManagerPrimary")
    public LocalContainerEntityManagerFactoryBean entityManagerPrimary() {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
//        vendorAdapter.setGenerateDdl(true);
        vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setShowSql(true);

        LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();

        factoryBean.setDataSource(primaryDataSource);
        factoryBean.setJpaVendorAdapter(vendorAdapter);
//        scanning for entity classes in the classpath
        factoryBean.setPackagesToScan(
                User.class.getPackageName() // domain(entity)
        );
        return factoryBean;
    }

}